package com.fxu.framework.core.holder;

import cn.hutool.core.util.StrUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 获取 HttpServletRequest
 * @author fangxu
 * @version 1.0.0
 */
public class RequestHolder {

    /**
     * 获取HttpServletRequest，异常NullPointerException
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequestNotNull() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 获取HttpServletRequest，有可能返回null
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequestMayNull() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }

    /**
     * 获得HttpServletRequest，抛异常
     * @return 返回IP地址
     */
    public static String getRequestIp() {
        return getRequestIp(getRequestMayNull());
    }

    /**
     * 获得HttpServletRequest，抛异常
     * @param request HttpServletRequest
     * @return 返回IP地址
     */
    public static String getRequestIp(HttpServletRequest request) {
        if (request == null) {
            return "127.0.0.1";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 对于通过多个代理的情况，第一个 IP 为客户端真实 IP，多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return StrUtil.isEmpty(ip) ? "127.0.0.1" : ip;
    }

    /**
     * 获取报头数据
     */
    public static String getHeaderMayNull(String key) {
        HttpServletRequest request = getRequestMayNull();
        if (request == null) return null;
        return request.getHeader(key);
    }
}